import { getNodeServerTask, pollingGetServerInfo } from "@/api/supply";

export const taskStatusEnum = {
  "-2": "执行失败",
  "-1": "超时取消",
  0: "等待中",
  1: "执行中",
  2: "执行成功",
};

export default {
  data() {
    return {
      serverLoading: false,
      nodeId: this.$route.query.id,
      askId: "",
      serverDetail: {},
      timer: null,
      taskStatusEnum,
      loadingText: ''
    };
  },
  computed: {
    nodeSearchRetList() {
      return this.serverDetail?.nodeSearchRetList || [];
    },
  },

  methods: {
    toggleServerLoading(bool) {
      this.serverLoading = bool || !this.serverLoading;
    },
    async getAskId() {
      this.toggleServerLoading(true);
      const { askId, code } = await getNodeServerTask({ nodeId: this.nodeId });
      if (code === 200 && askId) {
        this.askId = askId;
        this.startPolling();
      }
    },
    startPolling() {
      this.timer = setInterval(
        (() => (this.getServerInfo(), this.getServerInfo))(),
        5000
      );
    },
    async getServerInfo() {
      try {
        const { data } = await pollingGetServerInfo({
          askId: this.askId,
        });

        if (data.taskStatus !== 0 && data.taskStatus !== 1) {
          this.serverDetail = data;
          this.stopPolling();
        } else {
          this.loadingText = data.taskStatus ? "执行中..." : "等待执行，请稍后";
        }
      } catch (e) {
        this.stopPolling();
      }
    },
    stopPolling() {
      this.toggleServerLoading(false);
      clearInterval(this.timer);
      this.timer = null;
    },
  },
  mounted() {
    this.getAskId();
  },
};
